function setStorage(e, n, t) {
    e || window.localStorage.clear();
    var r = {data: n, expTime: t ? t : new Date};
    window.localStorage.setItem(e, JSON.stringify(r))
}
function getStorage(e) {
    var n = window.localStorage.getItem(e);
    return JSON.parse(n)
}
function alertMsg(e) {
    $(".main .message").remove(), $(".main").append(template("message_tmpl", {
        data: e.data || {},
        msg: e || {}
    })), $(".message .sure").on(clickEvent, function () {
        var n;
        return e.callback && (n = e.callback(), "boolean" == typeof n && !n) ? !1 : ($(".main .message").remove(), !1)
    }), $(".message .cancel" + (e.nomask ? "" : ",.message .maskbox")).on(clickEvent, function () {
        var n;
        return e.cancelback && (n = e.cancelback(), "boolean" == typeof n && !n) ? !1 : ($(".main .message").remove(), !1)
    })
}
var clickEvent = "ontouchstart" in window ? "touchstart" : "click";
!function () {
    function e(e) {
        return e.replace(b, "").replace(y, ",").replace(w, "").replace(k, "").replace(x, "").split(S)
    }

    function n(e) {
        return "'" + e.replace(/('|\\)/g, "\\$1").replace(/\r/g, "\\r").replace(/\n/g, "\\n") + "'"
    }

    function t(t, r) {
        function a(e) {
            return p += e.split(/\n/).length - 1, u && (e = e.replace(/\s+/g, " ").replace(/<!--[\w\W]*?-->/g, "")), e && (e = h[1] + n(e) + h[2] + "\n"), e
        }

        function o(n) {
            var t = p;
            if (s ? n = s(n, r) : i && (n = n.replace(/\n/g, function () {
                        return p++, "$line=" + p + ";"
                    })), 0 === n.indexOf("=")) {
                var a = f && !/^=[=#]/.test(n);
                if (n = n.replace(/^=[=#]?|[\s;]*$/g, ""), a) {
                    var o = n.replace(/\s*\([^\)]+\)/, "");
                    g[o] || /^(include|print)$/.test(o) || (n = "$escape(" + n + ")")
                } else n = "$string(" + n + ")";
                n = h[1] + n + h[2]
            }
            return i && (n = "$line=" + t + ";" + n), v(e(n), function (e) {
                if (e && !m[e]) {
                    var n;
                    n = "print" === e ? y : "include" === e ? w : g[e] ? "$utils." + e : $[e] ? "$helpers." + e : "$data." + e, k += e + "=" + n + ",", m[e] = !0
                }
            }), n + "\n"
        }

        var i = r.debug, c = r.openTag, l = r.closeTag, s = r.parser, u = r.compress, f = r.escape, p = 1,
            m = {$data: 1, $filename: 1, $utils: 1, $helpers: 1, $out: 1, $line: 1}, d = "".trim,
            h = d ? ["$out='';", "$out+=", ";", "$out"] : ["$out=[];", "$out.push(", ");", "$out.join('')"],
            b = d ? "$out+=text;return $out;" : "$out.push(text);",
            y = "function(){var text=''.concat.apply('',arguments);" + b + "}",
            w = "function(filename,data){data=data||$data;var text=$utils.$include(filename,data,$filename);" + b + "}",
            k = "'use strict';var $utils=this,$helpers=$utils.$helpers," + (i ? "$line=0," : ""), x = h[0],
            S = "return new String(" + h[3] + ");";
        v(t.split(c), function (e) {
            e = e.split(l);
            var n = e[0], t = e[1];
            1 === e.length ? x += a(n) : (x += o(n), t && (x += a(t)))
        });
        var T = k + x + S;
        i && (T = "try{" + T + "}catch(e){throw {filename:$filename,name:'Render Error',message:e.message,line:$line,source:" + n(t) + ".split(/\\n/)[$line-1].replace(/^\\s+/,'')};}");
        try {
            var j = new Function("$data", "$filename", T);
            return j.prototype = g, j
        } catch (E) {
            throw E.temp = "function anonymous($data,$filename) {" + T + "}", E
        }
    }

    var r = function (e, n) {
        return "string" == typeof n ? d(n, {filename: e}) : i(e, n)
    };
    r.version = "3.0.0", r.config = function (e, n) {
        a[e] = n
    };
    var a = r.defaults = {openTag: "<%", closeTag: "%>", escape: !0, cache: !0, compress: !1, parser: null},
        o = r.cache = {};
    r.render = function (e, n) {
        return d(e, n)
    };
    var i = r.renderFile = function (e, n) {
        var t = r.get(e) || m({filename: e, name: "Render Error", message: "Template not found"});
        return n ? t(n) : t
    };
    r.get = function (e) {
        var n;
        if (o[e]) n = o[e]; else if ("object" == typeof document) {
            var t = document.getElementById(e);
            if (t) {
                var r = (t.value || t.innerHTML).replace(/^\s*|\s*$/g, "");
                n = d(r, {filename: e})
            }
        }
        return n
    };

    var c = function (e, n) {
        return "string" != typeof e && (n = typeof e, "number" === n ? e += "" : e = "function" === n ? c(e.call(e)) : ""), e
    }, l = {"<": "&#60;", ">": "&#62;", '"': "&#34;", "'": "&#39;", "&": "&#38;"}, s = function (e) {
        return l[e]
    }, u = function (e) {
        return c(e).replace(/&(?![\w#]+;)|[<>"']/g, s)
    }, f = Array.isArray || function (e) {
            return "[object Array]" === {}.toString.call(e)
        }, p = function (e, n) {
        var t, r;
        if (f(e))for (t = 0, r = e.length; r > t; t++)n.call(e, e[t], t, e); else for (t in e)n.call(e, e[t], t)
    }, g = r.utils = {$helpers: {}, $include: i, $string: c, $escape: u, $each: p};

    r.helper = function (e, n) {
        $[e] = n
    };
    var $ = r.helpers = g.$helpers;

    r.onerror = function (e) {
        var n = "Template Error\n\n";
        for (var t in e)n += "<" + t + ">\n" + e[t] + "\n\n";
        "object" == typeof console && console.error(n)
    };

    var m = function (e) {
            return r.onerror(e), function () {
                return "{Template Error}"
            }
        },
        d = r.compile = function (e, n) {
            function r(t) {
                try {
                    return new l(t, c) + ""
                } catch (r) {
                    return n.debug ? m(r)() : (n.debug = !0, d(e, n)(t))
                }
            }

            n = n || {};
            for (var i in a)void 0 === n[i] && (n[i] = a[i]);
            var c = n.filename;
            try {
                var l = t(e, n)
            } catch (s) {
                return s.filename = c || "anonymous", s.name = "Syntax Error", m(s)
            }
            return r.prototype = l.prototype, r.toString = function () {
                return l.toString()
            }, c && n.cache && (o[c] = r), r
        }, v = g.$each,
        h = "break,case,catch,continue,debugger,default,delete,do,else,false,finally,for,function,if,in,instanceof,new,null,return,switch,this,throw,true,try,typeof,var,void,while,with,abstract,boolean,byte,char,class,const,double,enum,export,extends,final,float,goto,implements,import,int,interface,long,native,package,private,protected,public,short,static,super,synchronized,throws,transient,volatile,arguments,let,yield,undefined",
        b = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|\s*\.\s*[$\w\.]+/g,
        y = /[^\w$]+/g, w = new RegExp(["\\b" + h.replace(/,/g, "\\b|\\b") + "\\b"].join("|"), "g"),
        k = /^\d[^,]*|,\d[^,]*/g, x = /^,+|,+$/g, S = /^$|,+/;

    a.openTag = "{{", a.closeTag = "}}";

    var T = function (e, n) {
        var t = n.split(":"), r = t.shift(), a = t.join(":") || "";
        return a && (a = ", " + a), "$helpers." + r + "(" + e + a + ")"
    };

    a.parser = function (e) {
        e = e.replace(/^\s/, "");
        var n = e.split(" "), t = n.shift(), a = n.join(" ");
        switch (t) {
            case"if":
                e = "if(" + a + "){";
                break;
            case"else":
                n = "if" === n.shift() ? " if(" + n.join(" ") + ")" : "", e = "}else" + n + "{";
                break;
            case"/if":
                e = "}";
                break;
            case"each":
                var o = n[0] || "$data", i = n[1] || "as", c = n[2] || "$value", l = n[3] || "$index", s = c + "," + l;
                "as" !== i && (o = "[]"), e = "$each(" + o + ",function(" + s + "){";
                break;
            case"for":
                e = " for (" + a + "){";
                break;
            case"/for":
                e = "}";
                break;
            case"/each":
                e = "});";
                break;
            case"echo":
                e = "print(" + a + ");";
                break;
            case"print":
            case"include":
                e = t + "(" + n.join(",") + ");";
                break;
            default:
                if (/^\s*\|\s*[\w\$]/.test(a)) {
                    var u = !0;
                    0 === e.indexOf("#") && (e = e.substr(1), u = !1);
                    for (var f = 0, p = e.split("|"), g = p.length, $ = p[f++]; g > f; f++)$ = T($, p[f]);
                    e = (u ? "=" : "=#") + $
                } else e = r.helpers[t] ? "=#" + t + "(" + n.join(",") + ");" : "=" + e
        }
        return e
    }, "function" == typeof define ? define(function () {
        return r
    }) : "undefined" != typeof exports ? module.exports = r : this.template = r
}();
function winAlert(msg, d) {
    msg = msg || {};
    if (msg.onlyWin) $('.winAlert').remove();
    var set = {
        title: msg.title || '系统提示',
        body: msg.body || '',
        btn: msg.btn || '确定',
        nobtn: msg.nobtn || false,
        cancel: msg.cancel || '',
        fun: msg.fun || function () {
            return true;
        },
        cancelFun: msg.cancelFun || function () {
            return true;
        },
        maskShow: msg.maskShow || true,
        maskClick: msg.maskClick || false,
        closeFun: msg.closeFun || function () {
            return true;
        }
    };
    var obj = $(template('winAlert_tmpl', {msg: set, data: d || {}}));
    $('body').append(obj);
    obj.find('.close' + (set.maskClick ? ',.mark' : '')).click(function () {
        if (set.closeFun()) obj.remove();
    });
    obj.find('.sure').click(function () {
        if (set.fun()) obj.remove();
    });
    obj.find('.cancel').click(function () {
        if (set.cancelFun()) obj.remove();
    });
}

function menuActive(p, c) {
    $('.mlist > li').eq(parseInt(p, 10) || 0).addClass('active');
    if (typeof c !== "undefined") {
        $('.mlist>li.active .menuul > li').eq(parseInt(c, 10) || 0).addClass('active');
    }
}

//根据传入的html代码生成错误弹窗，并且支持根据type修改样式（type为className），并支持callback回调；
function toast(html, type, callback) {
    var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
    //清除原有的含.toast的元素
    $('.toast').remove();
    //新建一个.toast元素
    $('body').append('<div class="toast ' + (type || 'error') + '"><a href="#"><i class="icon ' + (type || 'error') + '"></i>' + (html || '') + '</a></div>');

    $('.toast').show().off().on(animationEnd, function () {
        $('.toast').hide();
        if (callback) callback();
    });
}

//为obj中所有input进行监听，在其数据错误的情况下给其附上错误样式，弹出错误提示框，并给submitBtn元素添加不可用样式
// 将callback方法放入submitBtn.click事件中，并只在数据正确是触发
function checkfrom(callback, obj, submitBtn) {
    //如果没有传入obj，则为obj赋初值$('.from_table')；
    if (!obj) obj = $('.from_table');
    //如果没有传入submitBtn，则为submitBtn赋初值$('.from_submit')；
    if (!submitBtn) submitBtn = $('.from_submit');
    //在obj中找到所有的input，并为他们的change(内容改变)事件blur(失去焦点)事件keyup(按下按键)事件附上函数；
    obj.find(':input').on('change blur keyup', function (e) {
        //将input的各个属性取出放入变量中
        var tagName = $(this)[0].tagName;
        var type = $(this).attr('type');
        var required = $(this).attr('required');
        var max = $(this).attr('max');
        var min = $(this).attr('min');
        var fieldname = $(this).attr('fieldname') || '';
        var errmsg = $(this).attr('errmsg');
        var name = $(this).attr('name');
        var val = $.trim((type == 'checkbox' || type == 'radio' ? $(':input[name=' + name + ']:checked').val() : $(this).val()));


        //如果input有required属性，则根据其值的存在情况为其附上"errIput"样式；
        if (required) {
            if (val) {
                $(this).removeClass('errIput');
            } else {
                $(this).addClass('errIput');
                //如果这个input框type为hidden、checkbox、radio、SELECT的话就弹出错误弹框；
                if (type == 'hidden' || type == 'checkbox' || type == 'radio' || tagName == 'SELECT') return toast(errmsg);
            }
        }

        //如果input有max属性且input的值大于max的值则弹出错误选框，并为其附上"errIput"样式
        if (max && val && parseFloat(max) < parseFloat(val)) {
            $(this).addClass('errIput');
            return toast(fieldname + '最大值不能大于' + max);
        }

        //如果input有min属性且input的值小于min的值则弹出错误选框，并为其附上"errIput"样式
        if (min && val && parseFloat(min) > parseFloat(val)) {
            $(this).addClass('errIput');
            return toast(fieldname + '最小值不能小于' + min);
        }

        //根据obj中是否还有含".errIput"样式的input来为提交按钮赋值
        if (obj.find('.errIput').length > 0) {
            submitBtn.addClass('gray_btn');
        } else {
            submitBtn.removeClass('gray_btn');
        }
    //    这里是为input禁止了滚轮事件；DOMMouseScroll为小胡添加，为了兼容火狐
    }).on('mousewheel DOMMouseScroll', function (e) {
        //通知web浏览器不要执行事件关联的默认动作(ps虽然有我的注释，但是最好是还自己去百度一下，印象才深)
        e.preventDefault();
    });

    //先为submitBtn清除事件关联函数，再为其click事件附上函数
    submitBtn.off().on('click', function () {
        var para = {};
        //在obj中找到所有的input，根据每个有name属性的input框的type为para添加para[name]属性；并触发blur事件
        obj.find(':input').each(function () {
            //将input的各个属性取出放入变量中
            var _this = $(this);
            var name = _this.attr('name');
            var type = _this.attr('type');
            var tagName = _this[0].tagName;
            var val = $.trim(_this.val());
            //如果input的name属性存在的话，根据input的type为para[name]赋值；
            if (name) {
                if (type == 'radio') {
                    //$.trim() 函数用于去除字符串两端的空白字符
                    para[name] = $.trim(obj.find(':input[name=' + name + ']:checked').val());
                } else if (type == 'checkbox') {
                    var tmp = [];
                    obj.find(':input[name=' + name + ']:checked').each(function () {
                        tmp.push($.trim($(this).val()));
                    });
                    para[name] = tmp.join(',');
                } else if (type == 'file') {
                } else if (tagName == 'SELECT') {
                    if (para[name]){
                        para[name]+=(","+$.trim(val))
                    }else {
                        para[name] = val;
                    }
                    if (!val && _this.attr('required')) {
                        toast(_this.attr('errmsg'));
                        _this.addClass('errIput');
                        return false;
                    }
                } else {
                    if (para[name]){
                        para[name]+=(","+$.trim(val))
                    }else {
                        para[name] = val;
                    }
                }
            }
        }).blur();
        console.log(para);
        //根据obj中有没有".errIput"判断有没有出错的input，再根据判断结果来修改按钮的样式，并且在没有出错的情况下执行回调函数
        if (obj.find('.errIput').length > 0) {
            submitBtn.addClass('gray_btn');
        } else {
            submitBtn.removeClass('gray_btn');
            if (callback) return callback(para, submitBtn);
        }
    });
}